﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

using System.IO;
using log4net;
using RollBackLib.src.utils;
using RollBackLib.src.core;
using RollbackLib.src.utils;

namespace RollBack.src.ui
{
    public partial class JobHistoryViewer : UserControl
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(BackupJob));

        private JobHistoryItems m_jobHistoryItems = new JobHistoryItems();

        public JobHistoryViewer()
        {
            InitializeComponent();
        }

        private ListViewItem createListViewItem(BackupStatistics stats)
        {
            ListViewItem item = new ListViewItem(new string[] {
                    stats.m_Id.m_Name,
                    stats.m_started.ToShortDateString() + "  " + stats.m_started.ToLongTimeString(),
                    stats.m_stopped.ToShortDateString() + "  " + stats.m_stopped.ToLongTimeString(),
                    stats.m_lastRunSuccess.ToString(),
                    stats.m_BackupType.ToString()
                });
            return item;
        }

        internal void addJobToHistory(BackupStatistics stats)
        {
            lock (m_jobHistoryItems)
            {
                // remove the last item from history if history is more than 50 items
                int len = m_jobHistoryItems.m_Items.Count;
                if (len > 50)
                {
                    m_jobHistoryItems.m_Items.RemoveAt(len - 1);
                }
                int len2 = listView1.Items.Count;
                if (len2 > 50)
                {
                    listView1.Items.RemoveAt(len2 - 1);
                }
                m_jobHistoryItems.m_Items.Insert(0,stats);
                ListViewItem item = createListViewItem(stats);
                listView1.Items.Insert(0, item);
                listView1.Sort();
            }
        }

        internal void clearHistory()
        {
            lock (m_jobHistoryItems)
            {
                listView1.Items.Clear();
                m_jobHistoryItems.m_Items.Clear();
            }
        }

        internal void saveHistoryData(string rootFilePath)
        {
            lock (m_jobHistoryItems)
            {
            	if(rootFilePath != null) {
	                string historyFile = getHistoryFilePath(rootFilePath);
	                try
	                {
	                    log.Info("Saving <" + m_jobHistoryItems.m_Items.Count + "> items to <" + historyFile + ">");
	                    XMLUtils.SaveObjectToXML(historyFile, m_jobHistoryItems);
	                }
	                catch (Exception e)
	                {
	                    AppUI.ShowException("Could not save Backup History file <" + historyFile + ">", e);
	                }
            	} else {
            		log.Warn("Did not save history since root file path is null");
            	}
            }
        }

        /// <summary>
        /// Save the history items.
        /// The name of the history file is derived from the rootFilePath, e.g. 
        /// if rootFilePath is C:\MyBackups\Pictures.xml then history file path will be C:\MyBackups\History.Pictures.xml
        /// </summary>
        /// <param name="rootFilePath"></param>
        internal void loadHistoryData(string rootFilePath)
        {
            lock (m_jobHistoryItems)
            {
                string historyFile = getHistoryFilePath(rootFilePath);
                try
                {
                    FileInfo f = new FileInfo(historyFile);
                    if (f.Exists)
                    {
                        log.Info("Loading history from <" + historyFile + "> FileSize=" + AppUtils.toHumanReadableSize(f.Length));
                        m_jobHistoryItems = (JobHistoryItems)XMLUtils.DeSerializeFromXML(historyFile, typeof(JobHistoryItems));
                        listView1.Items.Clear();
                        foreach (BackupStatistics stats in m_jobHistoryItems.m_Items)
                        {
                            ListViewItem item = createListViewItem(stats);
                            listView1.Items.Add(item);
                        }
                        log.Info("Loaded <" + m_jobHistoryItems.m_Items.Count + "> items into job history");
                    }
                }
                catch (Exception e)
                {
                    DialogResult result = AppUI.ShowMessage("Could not load Backup History file <" + historyFile + ">\r\nReason: " 
                        + e.Message 
                        + "\r\n\r\nDelete History file?",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {
                        File.Delete(historyFile);
                    }
                }
            }
        }

        private static string getHistoryFilePath(string rootFilePath)
        {
            FileInfo finfo = new FileInfo(rootFilePath);
            string historyFile = finfo.DirectoryName + "\\History." + finfo.Name;
            return historyFile;
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            lock (m_jobHistoryItems)
            {
                if (listView1.SelectedItems.Count >0 &&  m_jobHistoryItems.m_Items.Count >0)
                {
                    int index = listView1.SelectedItems[0].Index;
                    if (index <= m_jobHistoryItems.m_Items.Count)
                    {
                        jobRunStatsView1.addToJobRunStats(m_jobHistoryItems.m_Items[index]);
                    }
                }
            }
        }

    }


    [Serializable]
    public class JobHistoryItems
    {
        public List<BackupStatistics> m_Items = new List<BackupStatistics>();
    }
}
